package com.adapter;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.dstats.R;
import com.entities.Hero;
import com.entities.Item;
import com.entities.Match;
import com.entities.MatchDetailed;
import com.entities.PlayerDetailed;
import com.fetch.ImageLoader;


public class MatchsAdapter extends BaseAdapter {

	private static final String EMPTY = "empty_lg";
	private List<Match> data;
	private Context mContext;
	private LayoutInflater mInflater;
	private String accId;
	private ImageLoader imageLoader;
	private static SparseArray<String> items;
	private ImageLoader imageLoaderItems;
	Bitmap empty;
	private static final String _LG = "_lg";
	private static final String _PNG = ".png";
	private static final int rescale_h = 32;
	private static final int rescale_w = 43;
	private HashMap<String, Bitmap> savedBitmaps = new HashMap<String, Bitmap>();
	
	
	static class ViewHolder{
		private ImageView img;
		private TextView matchid;
		private TextView date;
		private TextView winLoss;
		private TextView duration;
		private TextView kda;
		private ImageView img0;
		private ImageView img1;
		private ImageView img2;
		private ImageView img3;
		private ImageView img4;
		private ImageView img5;
		
		
	}
	
	public MatchsAdapter(Context mContext, List<Match> data, String accId){
        this.data = data;
        this.mContext = mContext; 
        mInflater = LayoutInflater.from(mContext);
        this.accId = accId;
        empty = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.white);
		empty = Bitmap.createScaledBitmap(empty, rescale_w, rescale_h, false);
        imageLoader = new ImageLoader(mContext);
        imageLoaderItems = new ImageLoader(mContext);

   }
	
	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Match getItem(int arg0) {
		return data.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		return data.get(arg0).getMatch_id();
	}
	
	private SparseArray<String> getItems(){
		if(items==null){
		try {
			 items = Item.getAllItemsAsSparseArray(mContext.getAssets().open("items.json"));

		} catch (IOException e) {
		}
		}
		return items;
	}
	
	private void setImageFromString(String imageString, ImageView imageView){
		
		if(savedBitmaps.get(imageString)==null){
		int imgIdentifier = mContext.getResources().getIdentifier(imageString, "drawable", mContext.getPackageName());
		if(imgIdentifier!=0){
		Bitmap bm = BitmapFactory.decodeResource(mContext.getResources(), imgIdentifier);
		savedBitmaps.put(imageString, Bitmap.createScaledBitmap(bm, rescale_w, rescale_h, false));
		} else {
			if(imageString.equals(EMPTY)){
				imageView.setImageBitmap(empty);
				savedBitmaps.put(imageString, empty);
			} else {
			String urlItem0 = Item.baseImgUrl + imageString + _PNG;
			imageLoaderItems.DisplayImage(urlItem0, imageView, rescale_h, rescale_w);
			}
		}
		} 
		imageView.setImageBitmap(savedBitmaps.get(imageString));
		
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {

		ViewHolder holder;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.match_row, null);
			holder = new ViewHolder();  
			holder.img = (ImageView) convertView.findViewById(R.id.imageViewHero);
            holder.matchid = (TextView) convertView.findViewById(R.id.textViewMatchId);
    		holder.matchid.setTextColor(Color.BLACK);
            holder.date = (TextView) convertView.findViewById(R.id.textViewDate);
    		holder.date.setTextColor(Color.BLACK);
            holder.winLoss = (TextView) convertView.findViewById(R.id.textViewWinLoss);
            holder.winLoss.setTextColor(Color.BLACK);
            holder.duration = (TextView) convertView.findViewById(R.id.textViewDuration);
            holder.duration.setTextColor(Color.BLACK);
            holder.kda = (TextView) convertView.findViewById(R.id.textViewKDA);
            holder.kda.setTextColor(Color.BLACK);
            holder.img0 = (ImageView) convertView.findViewById(R.id.imageViewItem0);
            holder.img1 = (ImageView) convertView.findViewById(R.id.imageViewItem1);
            holder.img2 = (ImageView) convertView.findViewById(R.id.imageViewItem2);
            holder.img3 = (ImageView) convertView.findViewById(R.id.imageViewItem3);
            holder.img4 = (ImageView) convertView.findViewById(R.id.imageViewItem4);
            holder.img5 = (ImageView) convertView.findViewById(R.id.imageViewItem5);
            convertView.setTag(holder);
                  
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		if ( (position & 1) == 0 ) {
			convertView.setBackgroundColor(Color.TRANSPARENT);
			 } else { 
				 convertView.setBackgroundColor(Color.LTGRAY);
			 }

		final Match match = data.get(position);
		holder.matchid.setText(String.valueOf(match.getMatch_id()));
		holder.date.setText(getTimeDiff(new Date(match.getStart_time_in_miliseconds())));
		
		holder.winLoss.setText("");
		if(MatchDetailed.allMatchsDetailed.get(match.getMatch_id())!=null){
			MatchDetailed md = MatchDetailed.allMatchsDetailed.get(match.getMatch_id());
			if(md.playeroOfAccIdWon(accId)){
				holder.winLoss.setText("WIN");
				holder.winLoss.setTextColor(Color.GREEN);
			} else {
				holder.winLoss.setText("LOSS");
				holder.winLoss.setTextColor(Color.RED);
				
			}
			//imageLoader.DisplayImage(, imageView, rescale_h, rescale_w);
			PlayerDetailed playerDetailed = md.getPlayerOfAccId(accId);
			
			long duration = md.getDuration();
			int i = (int) (duration/60);
			holder.duration.setText(String.valueOf(i)+":"+String.valueOf(duration-i*60));
			if(playerDetailed!=null){
				
				SparseArray<String> sparseArray = getItems();

				String imgString0 = sparseArray.get(playerDetailed.getItem_0()) +_LG;
				String imgString1 = sparseArray.get(playerDetailed.getItem_1()) +_LG;
				String imgString2 = sparseArray.get(playerDetailed.getItem_2()) +_LG;
				String imgString3 = sparseArray.get(playerDetailed.getItem_3()) +_LG;
				String imgString4 = sparseArray.get(playerDetailed.getItem_4()) +_LG;
				String imgString5 = sparseArray.get(playerDetailed.getItem_5()) +_LG;
				setImageFromString(imgString0, holder.img0);
				setImageFromString(imgString1, holder.img1);								
				setImageFromString(imgString2, holder.img2);
				setImageFromString(imgString3, holder.img3);
				setImageFromString(imgString4, holder.img4);
				setImageFromString(imgString5, holder.img5);
				holder.kda.setText(String.valueOf(playerDetailed.getKills()) +"\n" + String.valueOf(playerDetailed.getDeaths()) +"\n" + String.valueOf(playerDetailed.getAssists()));
			}
		} else {
			holder.winLoss.setText("");	
			
			holder.img0.setImageBitmap(empty);
			holder.img1.setImageBitmap(empty);
			holder.img2.setImageBitmap(empty);
			holder.img3.setImageBitmap(empty);
			holder.img4.setImageBitmap(empty);
			holder.img5.setImageBitmap(empty);
			holder.duration.setText("");
			holder.kda.setText("");
			

		}
					
		Hero hero = Hero.getHeroById(mContext.getString(R.string.language), match.getHeroIdOfAccId(accId));
		int imgIdentifier = mContext.getResources().getIdentifier(hero.getImgResString(), "drawable", mContext.getPackageName());
		if(imgIdentifier!=0){
		Bitmap bm = BitmapFactory.decodeResource(mContext.getResources(), imgIdentifier);
		holder.img.setImageBitmap(Bitmap.createScaledBitmap(bm, 103, 55, false));
		} else {
			imageLoader.DisplayImage(hero.getImgLgUrl() + _PNG, holder.img, 55, 103);
		}
		
		return convertView;
	}

	private String getTimeDiff(Date date) {
		Date curDate = new Date();
		
		long diff = curDate.getTime() - date.getTime();
		long mins = diff/60000;
		long hours = mins/60;
		long days = hours/24;
		long months = days/365/12;
		long years = months /12;
		Resources r = mContext.getResources();
		String toPut;
		if(years>=1){
			if(years==1) toPut = String.valueOf(years) + " " + r.getString(R.string.year_ago);
			else toPut = String.valueOf(years) + " " + r.getString(R.string.years_ago);
		} else if (months>=1){
			if(months==1) toPut = String.valueOf(months) + " " + r.getString(R.string.month_ago); 
			else toPut = String.valueOf(months) + " " + r.getString(R.string.months_ago);
		} else if (days>=1) {
			if(days==1) toPut = String.valueOf(days) + " " + r.getString(R.string.day_ago);
			else toPut = String.valueOf(days) + " " + r.getString(R.string.days_ago);
		} else if (hours>=1){
			if(hours==1)  toPut = String.valueOf(hours) + " " + r.getString(R.string.hour_ago);
			else toPut = String.valueOf(hours) + " " + r.getString(R.string.hours_ago);
		} else {
			if(mins==1 || mins ==0) toPut = String.valueOf(mins) + " " + r.getString(R.string.minute_ago);
			else toPut = String.valueOf(mins) + " " + r.getString(R.string.minutes_ago);
		}
		return toPut;
	}

	

}
